package org.biogroovy.net

/**
 * This class allows you to easily create a URL and bind parameters to it.
 */
class URLMap {

	/** The path of the URL. i.e 'http://whatever.com?' */
	private String path = null;

	/**
	 * a map of key-value pairs that will become the
	 * request parameters (basically everything that 
	 * follows the question mark).
	 */ 
	private Map attributes = null;

	/**
	 * Constructor.
	 * @param path The path of the URL. i.e 'http://whatever.com?'
	 * @param attributes 	a map of key-value pairs that will become the 
	 * 						request parameters (basically everything that 
	 * 						follows the question mark).
	 */
	public URLMap(String path, Map<String, String> attributes){
		this.path = path;
		this.attributes = attributes;
	}

	/**
	 * This method generates a URL.
	 */
	@Override
	public String toString(){

		String url = null;
		if (this.path == null && this.attributes == null){
			throw new RuntimeException("The path and attributes must be set first.");
		}
		url = this.path;

		this.attributes.keySet().eachWithIndex(){key, index->

			if (index > 0){
				url += "&${key}=${this.attributes.get(key)}";
			}else {
				if (url.contains("?")){
					url += "&${key}=${this.attributes.get(key)}";
				}else{
					url += "?${key}=${this.attributes.get(key)}";
				}
			}
		};
		url = url.replaceAll(" ", "+")
		return url;
	}

	/**
	 * This method generates a URL.
	 */
	public URL toURL(){
		return new URL(this.toString());
	}

	/**
	 * This method creates an input stream from the URL.
	 * @return
	 * @throws IOException  If there is a problem opening the input stream.
	 */
	public InputStream toInputStream() throws IOException{
		return toURL().openStream();
	}
}